package org.bbb.library1.handlers;

/*******************************************************************************
 * Copyright (c) 2007 Finalist IT Group B.V.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *    Rob Schellhorn - initial API and implementation
 *******************************************************************************/

import org.bbb.library1.editors.BookEditor;
import org.bbb.library1.editors.BookEditorInput;
import org.bbb.library1.model.Book;
import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.handlers.HandlerUtil;

/**
 * @author Rob Schellhorn
 */
public class OpenBookHandler extends AbstractHandler {

   /*
    * @see org.eclipse.core.commands.AbstractHandler#execute(org.eclipse.core.commands.ExecutionEvent)
    */
   @Override
   public Object execute(ExecutionEvent event) throws ExecutionException {
      IWorkbenchWindow window = HandlerUtil.getActiveWorkbenchWindowChecked(event);
      ISelection selection = HandlerUtil.getCurrentSelection(event);

      if (selection instanceof IStructuredSelection) {

         Book book = (Book) IStructuredSelection.class.cast(selection).getFirstElement();
         if (book != null) {

            try {
               IWorkbenchPage page = window.getActivePage();

               IEditorInput input = new BookEditorInput(book);
               page.openEditor(input, BookEditor.EDITOR_ID);
            } catch (PartInitException e) {
               throw new ExecutionException("Failed to open an editor", e);
            }
         }
      }

      return null;
   }
}